/**
 *  Copyright 2002-2009 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package foo.bar.blog.web.action.registered;

import foo.bar.blog.core.domain.User;
import foo.bar.blog.core.services.UserService;
import foo.bar.blog.web.action.BaseActionBean;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.*;
import org.jsecurity.SecurityUtils;
import org.perf4j.aop.Profiled;

/**
 * @author tmjee
 * @version $Date: 2009-06-06 13:26:52 +0000 (Sat, 06 Jun 2009) $ $Id$
 */
public class ProfileActionBean extends BaseActionBean implements ValidationErrorHandler  {

    public static final String VIEW = "registered/profile.jsp";
    public static final String VIEW_CHANGE_PASSWORD = "registered/profile_changePassword.jsp";
    public static final String VIEW_GENERAL = "registered/profile_general.jsp";

    @ValidateNestedProperties({
        @Validate(field="email", converter = EmailTypeConverter.class, required = true, trim=true, on={"save"}),
        @Validate(field="password", required=true, trim=true, on={"changePassword"})
    })
    private User user;

    @Validate(required=true, trim=true, on={"changePassword"})
    private String password;

    @Validate(required=true, trim=true, on={"changePassword"})
    private String confirmPassword;

    private UserService userService;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getConfirmPassword() {
        return confirmPassword;
    }

    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }

    @DefaultHandler
    @Profiled(tag="ProfileActionBean_view", logFailuresSeparately = true)
    public Resolution view() {
        user = retrieveCurrentUser();
        return new ForwardResolution(generateThemePath(VIEW));
    }


    @Profiled(tag="ProfileActionBean_viewGeneral", logFailuresSeparately = true)
    public Resolution viewGeneral() {
        user = retrieveCurrentUser();
        return new ForwardResolution(generateThemePath(VIEW_GENERAL));
    }


    @Profiled(tag="ProfileActionBean_viewChangePassword", logFailuresSeparately = true)
    public Resolution viewChangePassword() {
        return new ForwardResolution(generateThemePath(VIEW_CHANGE_PASSWORD));
    }



    @ValidationMethod(on={"changePassword"})
    public void validate_changePassword(ValidationErrors errors) {
        if (password == null || confirmPassword == null || (!password.equals(confirmPassword))) {
            errors.add("password", new LocalizableError("errors.passwordMismatch"));
        }
    }
    @Before(stages = LifecycleStage.BindingAndValidation, on="changePassword")
    public void before_changePassword() {
         user = retrieveCurrentUser();
    }
    @Profiled(tag="BlogsProfileActionBean_changePassword", logFailuresSeparately = true)
    public Resolution changePassword() {
        userService.changePassword(user, password);
        getContext().getMessages().add(new LocalizableMessage("foo.bar.blog.web.action.registered.ProfileActionBean.messages.changePasswordSuccess"));
        return new ForwardResolution(generateThemePath(VIEW_CHANGE_PASSWORD));
    }



    @Before(stages = LifecycleStage.BindingAndValidation, on = "save")
    public void before_save() {
        user = retrieveCurrentUser();
    }
    @Profiled(tag="BlogsProfileActionBean_save", logFailuresSeparately = true)
    public Resolution save() {
        userService.saveOrUpdateUser(user);
        getContext().getMessages().add(new LocalizableMessage("foo.bar.blog.web.action.registered.ProfileActionBean.messages.saveSuccess"));
        return new ForwardResolution(generateThemePath(VIEW_GENERAL));
    }


    protected User retrieveCurrentUser() {
        long userId = ((User)SecurityUtils.getSubject().getPrincipal()).getId();
        return userService.getUserById(userId);
    }

    @SpringBean("userService")
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    @Profiled(tag="BlogsProfileActionBean_handleValidationErrors", logFailuresSeparately = true)
    public Resolution handleValidationErrors(ValidationErrors errors) throws Exception {
        if ("save".equals(getContext().getEventName())) {
            return new ForwardResolution(generateThemePath(VIEW_GENERAL));    
        }
        return null;
    }
}
